package com.swinw.asumall.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.swinw.asumall.search.constant.EsConstant;
import com.swinw.asumall.search.service.ElasticsearchSaveService;
import com.swinw.common.to.SkuEsModel;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;

@Service
public class ElasticsearchSaveServiceImpl implements ElasticsearchSaveService {

    @Autowired
    RestHighLevelClient restHighLevelClient;

    /**
     * 将商品信息保存到Elasticsearch中
     * @param skuEsModels
     */
    @Override
    public boolean saveSkuToEs(List<SkuEsModel> skuEsModels) throws IOException {
        //执行保存操作
        BulkRequest bulkRequest = new BulkRequest();
        for (SkuEsModel skuEsModel : skuEsModels) {
            IndexRequest request = new IndexRequest();
            request.index(EsConstant.ES_INDEX);
            request.id(skuEsModel.getSkuId().toString());
            String jsonString = JSON.toJSONString(skuEsModel);
            request.source(jsonString,XContentType.JSON);
            bulkRequest.add(request);
        }

        BulkResponse bulk = restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);
        boolean b = bulk.hasFailures();
        System.out.println(b + "++++++++++++++++++++\n\n\n");
        return b;

    }
}
